Java8 Stream 流中的匹配查找方法

1、Java8 Stream 流中的匹配查找方法

findAny:查找任何一个就返回 Optional
findFirst:查找到第一个就返回 Optional
anyMatch:匹配上任何一个则返回 Boolean
allMatch:匹配所有的元素则返回 Boolean

public enum SwitchEnum {

    ONE(1, "x"),
    TWO(2, "x"),
    THREE(3, "x2");

    private int type;
    private String name;

    SwitchEnum(int type, String name) {
        this.type = type;
        this.name = name;
    }

    // 查找某一个枚举值
    public static SwitchEnum findAny(int type) {
        return Arrays.stream(SwitchEnum.values())
                .filter(switchEnum -> switchEnum.getType() == type)
                .findAny()
                .orElse(null);
    }

    // 匹配到第一个枚举值就返回
    public static SwitchEnum findFirst(String name) {
        return Arrays.stream(SwitchEnum.values())
                .filter(switchEnum -> switchEnum.getName().equals(name))
                .findFirst()
                .orElse(null);
    }


    // 枚举匹配
    public static boolean anyMatch(int type) {
        return Arrays.stream(SwitchEnum.values())
                //匹配任何一个则返回
                .anyMatch(switchEnum -> switchEnum.getType() == type);
    }

    // 枚举匹配
    public static boolean allMatch(String name) {
        return Arrays.stream(SwitchEnum.values())
                //匹配所有
                .allMatch(switchEnum -> switchEnum.getName().equals(name));
    }


    public int getType() {
        return type;
    }


    public String getName() {
        return name;
    }

    public static void main(String[] args) {
        System.out.println("findAny============>" + findAny(1));
        System.out.println("findFirst============>" + findFirst("x"));
        System.out.println("anyMatch============>" + anyMatch(2));
        System.out.println("anyMatch============>" + allMatch("x"));
    }
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值